﻿using System;
using System.Web.UI;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Xml;
using System.Web;
using ServBus.ListForm2013.Utility;
using FluentRibbon.Libraries;
using FluentRibbon.Definitions;
using FluentRibbon;
using Microsoft.SharePoint.WebControls;
using FluentRibbon.Definitions.Controls;

namespace ServBus.ListForm2013.ListFormWFWebPart
{
    public partial class ListFormWFWebPartUserControl : UserControl
    {

        #region Parameters

        public System.Web.UI.HtmlControls.HtmlGenericControl container;

        public static bool urlMode = true;
        public static string siteName = string.Empty;//
        public static string webUrl = "";//"Test";
        public static string listId = "";//"test";
        public static string contentTypeId = "";
        public static string listName = "";//"test";
        public static string itemId = "";//string.Empty;
        public static string importFields = "";

        public ListFormWFWebPart webpart { get; set; }
        XmlNamespaceManager xNameSpace;

        static string pulishUrl = string.Empty;
        #endregion

        #region Page Method
        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
                if (ribbon != null)
                {
                    ribbon.TrimById("Ribbon.WebPartPage");
                }
               
                DecodeUrl();
                bool parameterStatus = true;
                #region Set Parameters
                   

                    siteName = SPContext.Current.Site.Url;

                    webUrl = Page.Request.Url.ToString();
                    webUrl = webUrl.Substring(0, webUrl.IndexOf("/Lists/",StringComparison.OrdinalIgnoreCase));

                    if (!string.IsNullOrEmpty(Request("listId")))
                    {
                        listId = Convert.ToString(Request("listId"));
                    }
                    else
                    {
                        parameterStatus = false;
                    }

                    if (!string.IsNullOrEmpty(Request("ID")))
                    {
                        itemId = Convert.ToString(Request("ID"));
                    }
                    if (!string.IsNullOrEmpty(Request("itemId")))
                    {
                        itemId = Convert.ToString(Request("itemId"));
                    }                    
                    if (!string.IsNullOrEmpty(Request("ctypeId")))
                    {
                        contentTypeId = Convert.ToString(Request("ctypeId"));
                    }
                    else
                    {
                            parameterStatus = false;
                    }
                

                #endregion

                if (!Page.IsPostBack)
                {
                    if (parameterStatus)
                    {
                        GenerateEditForm();
                    }
                    else
                    {
                        exView.Visible = true;
                        exView.Text = "Parameters missed, please check!";
                    }
                }
            }
            catch (Exception ex)
            {
                //xDocView.Visible = false;
                exView.Visible = true;
                exView.Text = ex.ToString();
            }
        }

        #endregion

        #region Private Method

        private void GenerateEditForm()
        {
            #region comment showRibbon
            //if (showRibbon)
            //{
            //    #region add ribbon buttons
            //    var tabDefinition = new TabDefinition()
            //    {

            //        Id = "EditRibbon",
            //        Title = "Edit",
            //        Groups = new GroupDefinition[]
            //    {
            //        new GroupDefinition()
            //        {
            //            Id = "commitGroup",
            //            //Title = Resource.GetString("RibbonGroup_Submit"),
            //            Title = "Commit",
            //            Template = GroupTemplateLibrary.SimpleTemplate,
            //            Controls = new ControlDefinition[]
            //            {
            //                new ButtonDefinition()
            //                {
            //                    Id = "CloseButton",
            //                    //Title = Resource.GetString("Btn_Close"),
            //                    Title ="Close",
            //                    CommandJavaScript = "closeFormPart()",
            //                    //Image = ImageLibrary.GetStandardImage(9, 14,_currentlcid)
            //                    Image = new ImageDefinition()
            //                    { 
            //                        Url32 = "/_layouts/15/ListForm2013/Images/Close32.png"
            //                    }
            //                }                                        
            //            }
            //        },
            //        new GroupDefinition()
            //        {
            //            Id = "actionsGroup",
            //            //Title = Resource.GetString("RibbonGroup_Submit"),
            //            Title = "Actions",
            //            Template = GroupTemplateLibrary.SimpleTemplate,
            //            Controls = new ControlDefinition[]
            //            {
            //                new ButtonDefinition()
            //                {
            //                    Id = "DeleteButton",
            //                    //Title = Resource.GetString("Btn_Save"),
            //                    Title = "Delete Item",
            //                    CommandJavaScript = "deleteFormPart();",
            //                    //Image = ImageLibrary.GetStandardImage(8, 13,_currentlcid),
            //                    Image = new ImageDefinition()
            //                    { 
            //                        Url32 = "/_layouts/15/ListForm2013/Images/Delete32.png"
            //                    }
            //                }                                 
            //            }
            //        }
            //    }
            //    };



            //    RibbonController.Current.AddRibbonTabToPage(tabDefinition, this.Page, true);

            //    #endregion
            //}
            #endregion
            string url = webUrl + Constants.WF_PAGE_INNER + "?itemId=" + itemId + "&listId=" + listId + "&ctype=" + contentTypeId;
            if (!string.IsNullOrEmpty(importFields)) url = url + importFields;
            container.Attributes.Add("src", url);
        }

        

        private Dictionary<string, string> urlParamDic = new Dictionary<string, string>();
        private void DecodeUrl()
        {
            String currurl = HttpUtility.UrlDecode(HttpContext.Current.Request.RawUrl);
            importFields = "";
            String querystring = null;

            // Check to make sure some query string variables
            // exist and if not add some and redirect.
            int iqs = currurl.IndexOf('?');
            if (iqs >= 0)
            {
                querystring = (iqs < currurl.Length - 1) ? currurl.Substring(iqs + 1) : String.Empty;
            }

            // Parse the query string variables into a NameValueCollection.
            System.Collections.Specialized.NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

            // Iterate through the collection.
            foreach (String s in qscoll.AllKeys)
            {
                if (s.StartsWith("~")) importFields += (string.IsNullOrEmpty(s)) ? s + "=" + qscoll[s] : "&" + s + "=" + qscoll[s];
                urlParamDic.Add(s.ToUpper(), qscoll[s].ToUpper());
                
            }
        }

        private string Request(string param)
        {
            string returnValue = string.Empty;

            if (urlParamDic.ContainsKey(param.ToUpper()))
            {
                returnValue = urlParamDic[param.ToUpper()];
            }
            return returnValue;
        }
        #endregion
    }
}
